import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_footer.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/notice.dart';
import 'package:kxy_flutter_app/view/home/notice/notice_item_widget.dart';
import 'package:kxy_flutter_app/view/root/view_model/navigation_model.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class NoticeView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return NoticeViewState();
  }
}

class NoticeViewState extends State<NoticeView> {
  int page = 1;
  int totalCount = 0;
  List<Notice> noticeList = new List<Notice>();
  Future loadFuture;
  RefreshController refreshController = new RefreshController();

  @override
  void initState() {
    loadFuture = reload();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<NavigationModel>(
      builder: (cxt, vm, child) => WillPopScope(
        child: Scaffold(
          appBar: AppBar(title: Text('消息通知')),
          body: FutureBuilder(
            future: loadFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return noticeListWidget();
              }
              return LoadingWidget();
            },
          ),
        ),
        onWillPop: () async {
          await vm.refreshNoticeCount();
          return Future.value(true);
        },
      ),
    );
  }

  Widget noticeListWidget() {
    if (noticeList.length == 0) {
      return EmptyWidget(onRefresh: reload);
    }

    SlidableController slidableController = new SlidableController();
    return SmartRefresher(
      controller: refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: RefreshHeader(),
      footer: RefreshFooter(),
      onLoading: () async {
        if (totalCount > noticeList.length) {
          await loadMore();
          refreshController.loadComplete();
        } else {
          refreshController.loadNoData();
        }
      },
      onRefresh: () async {
        await reload();
        refreshController.refreshCompleted();
      },
      child: ListView.builder(
        itemBuilder: (cxt, index) {
          return NoticeItemWidget(
            notice: noticeList[index],
            onRemove: removeItem,
            controller: slidableController,
          );
        },
        itemCount: noticeList.length,
      ),
    );
  }

  Future removeItem(String noticeId) async {
    setState(() {
      noticeList.removeWhere((x) => x.id == noticeId);
    });
    await Http.instance.post('/news-app/notice/del', params: {
      'noticeId': noticeId,
      'userId': Auth.instance.userId,
    });
  }

  Future reload() async {
    page = 1;
    noticeList.clear();
    await loadMore();
  }

  Future loadMore() async {
    var res = await Http.instance.post(
      '/news-app/notice/page',
      params: {
        'page': page,
        'userId': Auth.instance.userId,
      },
    );

    setState(() {
      totalCount = res.data['totalCount'];
      (res.data['list'] as List).forEach((item) {
        var notice = Notice.fromJson(item);
        noticeList.add(notice);
      });
      page++;
    });
  }
}
